﻿using WH.Contracts.Systems.Menus;
using WH.Model.OrgContext;
using WH.Model.Systems;
using WH.Repositories.BaseRepositories;
using WH.Repositories.IRepositories.ISystem;
using Rw.Core.Common.Paging;
using WH.Common.Paging;
using SqlSugar;

namespace WH.Repositories.Repositories.System
{
    public class MenuRepository : BaseRepository<MenuEntity>, IMenuRepository
    {
        public MenuRepository(ISqlSugarClient dbContext, OrganizationContext organizationContext) : base(dbContext, organizationContext)
        {
        }

        /// <summary>
        /// 按条件查询菜单列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<IList<MenuEntity>> GetMenusAsync(MenuFilter filter)
        {
            var query = Query;
            if (!string.IsNullOrWhiteSpace(filter.Keyword))
            {
                filter.Keyword = filter.Keyword.Trim();
                query = query.Where(m => m.Name.Contains(filter.Keyword));
            }

            if (!string.IsNullOrWhiteSpace(filter.Name))
            {
                filter.Name = filter.Name.Trim();
                query = query.Where(map => map.Name.Contains(filter.Name));
            }

            if (!string.IsNullOrWhiteSpace(filter.OrganizationId))
            {
                query = query.Where(map => map.OrganizationId.Equals(filter.OrganizationId));
            }

            if (filter.Status.HasValue)
            {
                query = query.Where(map => map.Status == filter.Status.Value);
            }

            var list = await query.OrderByDescending(m => m.SortNo).ToListAsync();//.ToTreeAsync(m => m.Children, m => m.ParentId, 0)
            return list;
        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<IPagedList<MenuEntity>> GetMenusByPageAsync(PageParam pager, MenuFilter filter)
        {
            var query = Query;
            if (!string.IsNullOrWhiteSpace(filter.Keyword))
            {
                filter.Keyword = filter.Keyword.Trim();
                query = query.Where(m => m.Name.Contains(filter.Keyword));
            }

            if (!string.IsNullOrWhiteSpace(filter.Name))
            {
                filter.Name = filter.Name.Trim();
                query = query.Where(map => map.Name.Contains(filter.Name));
            }

            if (!string.IsNullOrWhiteSpace(filter.OrganizationId))
            {
                query = query.Where(map => map.OrganizationId.Equals(filter.OrganizationId));
            }

            if (filter.Status.HasValue)
            {
                query = query.Where(map => map.Status == filter.Status.Value);
            }

            var paged = await query.OrderByDescending(m => m.SortNo).ToPagedOrderByListAsync(pager);
            return paged;
        }
    }
}
